import getpath
import os
import logging
import csv
import myglobal
import sample
def newSample(samples, sampleid, ele, wave, conc, mass, volume):
    # can not same sampleid followed
    if len(samples) >= 1:
        sample = samples[-1]
        if sampleid == sample["sampleid"]:  # same sampleid with last
            at2 = myglobal.inItems(sample["items"], (ele, wave))
            if at2:  # same element wave donot capture
                pass
            else:
                sample["conc"].append(conc)
                sample["items"].append((ele, wave))
            return False
        else:
            samples.append({"mass": mass, "volume": volume, "sampleid": sampleid, "conc": [
                conc], "items": [(ele, wave)]})
            return True
    else:  # []
        samples.append({"mass": mass, "volume": volume, "sampleid": sampleid, "conc": [
            conc], "items": [(ele, wave)]})
        return True
def getdata(fname):
    file=open(fname, encoding="gb18030")
    csv_reader = csv.reader(file)
    row_index = 0
    samples = []
    create_table = False
    for row in csv_reader:
        logging.info(row)
        if row_index >= 1:
            sampleid = row[0]
            if sampleid=="":
                break
            (ele, wave) = row[2].split(" ")
            conc = row[4]
            mass = row[14]
            volume = myglobal.myfloat(row[15])*100
            n = newSample(samples, sampleid,
                               ele, wave, conc, mass, volume)
            # if n:
            #     if (len(samples) - 2) >= 0:  # save last
            #         sample = samples[len(samples) - 2]
            #         if not create_table:
            #             self.cTable(sample)
            #             create_table = True
            #         self.iTable(sample)
            # else:
            #     pass
        else:
            pass
        row_index += 1
    file.close()
    print(len(samples))
    print(samples[0])    
    print(samples[-1])    
    return samples
def toObjects(data):
    # print(data)
    r=[]
    for one in data:
        s=sample.SampleICP()
        s.sampleid=one["sampleid"]
        s.mass=one["mass"]
        s.volume=one["volume"]
        for i in range(len(one["items"])):
            item=one["items"][i]
            # itemCls=sample2.Item(item[0],item[1],one["conc"][i])
            # s.__setattr__(item[0],itemCls)
            s.items[(item[0],item[1])]=s.sampleid=one["sampleid"]
        r.append(s)
    return r
def test_getdata():
    fname=os.path.join(getpath.getpath(),"..","data","725.csv")
    data=getdata(fname)
    data=toObjects(data)
    return data
if __name__=="__main__":
    data=test_getdata()
    print(data)
    print(data[0])
    print(data[1])
    print(data[-1])